#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash OpenCV-4.5.5.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

if [[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]]; then
    echo "请输入正确的构建路径"
    exit 1
fi
if [[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]]; then
    echo "请输入正确的安装路径"
    exit 1
fi

buildpath=$1
installpath=$2
if [[ "$1" =~ .*/$ ]]; then buildpath=${buildpath%/*}; fi
if [[ "$2" =~ .*/$ ]]; then installpath=${installpath%/*}; fi
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1
set -e
yum install -y wget tar cmake environment-modules
yum install -y python3 python3-numpy libjpeg libtiff giflib gstreamer* libgtk* gtk2-devel libxvidcore* libx264* libgtk-3* gtk3-devel tbb openblas lapack jasper hdf5-devel protobuf
wget -t 10 -c -P $buildpath https://github.com/opencv/opencv/archive/refs/tags/4.5.5.tar.gz

tar xf $buildpath/4.5.5.tar.gz -C $buildpath && rm -rf $buildpath/4.5.5.tar.gz
cd $buildpath/opencv-4.5.5
mkdir build
cd build
export CC=`which clang`
export CXX=`which clang++`
export FC=`which flang`
cmake -DCMAKE_BUILD_TYPE=RELEASE -DCMAKE_INSTALL_PREFIX=$installpath/opencv ..
make -j$(nproc)
make install
unset CC
unset CXX
unset FC

cat >"$installpath/opencv/opencv_modulefiles" <<EOF
#%Module1.0
conflict opencv
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
        set modfile_path [file dirname \$modfile]
            return \$modfile_path
    }
set pwd [getModulefileDir]
set OPENCV \$pwd
setenv OPENCV \$OPENCV
prepend-path OpenCV_DIR \$OPENCV

EOF
rm -rf $buildpath/opencv-4.5.5
